<?php

declare(strict_types=1);

namespace app\api\model;

use app\api\model\Stage as ModelStage;
use app\api\model\Chapter as ModelChapter;
use think\facade\Request;

/**
 * 周期模型
 */
class Week extends Base
{
    protected $autoWriteTimestamp = 'datetime';


    /**
     * # 增加周期课程
     * @param array $data
     * @return object
     */
    public static function addWeekCourse($data)
    {
        $week = Week::getWeek($data['stage_id'], 'desc', 'find');
        if (empty($week->toArray())) {
            $week_name = 0;
        } else {
            $week_name = $week->week_name;
        }
        $data['week_name'] = ++$week_name;
        $success = Week::create($data);
        return $success;
    }

    /**
     * # 修改周期课程状态
     * @param string|int $id
     * @param string|int $status
     * @return bool
     */
    public static function editWeekCourse($id, $status)
    {
        $week = Week::find($id);
        if (empty($week)) {
            return false;
        }
        $status = $status == 0 ? 1 : 0;
        $week->is_online = $status;
        $success = $week->save();
        return $success;
    }

    /**
     * 
     * 编辑周期课程
     * 
     */
    public static function updateWeekCourse($id, $data)
    {
        $week = Week::find($id);
        if (empty($week)) {
            return [];
        }
        $week->title = $data['title'];
        $success = $week->save() === true ? true : [];
        return $success;
    }

    /**
     * # 获取阶段下周期
     * @param string|array|int $stage_ids
     * @param string $order
     * @param string $option
     * @return false|object
     */
    public static function getWeek($stage_ids, $order = 'asc', $option = 'select')
    {
        $field = 'id,week_name,title,is_online,sort,create_time,stage_id';
        $where = [];
        if (is_string($stage_ids) || is_int($stage_ids)) {
            $where[] = ['stage_id', '=', $stage_ids];
        } else if (is_array($stage_ids)) {
            $where[] = ['stage_id', 'in', $stage_ids];
        } else {
            return false;
        }
        $week = Week::where($where)->field($field)->order('week_name', $order)->$option();
        return $week;
    }

    /**
     * 切换周期名字
     */

    public static function onAfterRead($user)
    {
        if (Request::action() == 'create') return;
        if (isset($user->week_name)) {
            $user->weekName = '第' . $user->week_name . '周';
        }
    }

    /**
     * # 验证课程是否存在
     * @param string|int $week_id
     * @return false|array
     */

    public static function verifyCourse($week_id)
    {
        $week = Week::find($week_id);
        if(empty($week)){
            return false;
        }
        return $week;
    }
}
